package com.mall.pay.wxpay.util;

import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.text.DecimalFormat;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.params.ClientPNames;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.util.EntityUtils;
import org.jdom.Document;
import org.jdom.Element;
import org.jdom.JDOMException;
import org.jdom.input.SAXBuilder;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.mall.pay.wxpay.util.http.HttpClientConnectionManager;
import com.mall.web.service.WxService;

public class WxApi {
	public static DefaultHttpClient httpclient;
	public static String FAIL = "FAIL";
	public static String SUCCESS = "SUCCESS";
	private static Logger logger = LoggerFactory.getLogger(WxService.class);
	static {
		httpclient = new DefaultHttpClient();
		httpclient = (DefaultHttpClient) HttpClientConnectionManager.getSSLInstance(httpclient);
	}
	public static boolean orderIsSuccess(String url, String xmlParam) {
		try {
			Map map = orderQuery(url, xmlParam);
			if (!map.isEmpty() && SUCCESS.equals(map.get("trade_state").toString())) {
				return true;
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return false;
	}

	/**
	 * description:获取扫码支付连接
	 * 
	 * @param url
	 * @param xmlParam
	 * @return
	 * @author ex_yangxiaoyi
	 * @see
	 */
	public static String getResponseStr(String url, String xmlParam) {
		DefaultHttpClient client = new DefaultHttpClient();
		client.getParams().setParameter(ClientPNames.ALLOW_CIRCULAR_REDIRECTS, true);
		HttpPost httpost = HttpClientConnectionManager.getPostMethod(url);
		String jsonStr = FAIL;
		try {
			httpost.setEntity(new StringEntity(xmlParam, "UTF-8"));
			HttpResponse response = client.execute(httpost);
			jsonStr = EntityUtils.toString(response.getEntity(), "UTF-8");
		} catch (Exception e) {
			e.printStackTrace();
		}
		return jsonStr;
	}

	/**
	   *description:获取预支付id
	   *@param url
	   *@param xmlParam
	   *@return String
	   */
	  public static String getPayNo(String url,String xmlParam){
		  String prepay_id = "";
	     try {
	    	 String jsonStr = getResponseStr(url, xmlParam);
	    	 System.out.println(jsonStr);
	 		logger.info("统一下单响应---"+jsonStr);
		    if(jsonStr.indexOf("FAIL")!=-1){
		    	return prepay_id;
		    }
		    Map map = doXMLParse(jsonStr);
		    prepay_id  = (String) map.get("prepay_id");
		} catch (Exception e) {
			e.printStackTrace();
		}
		return prepay_id;
	  }
	  
	public static String getCodeUrl(String url, String xmlParam) throws Exception {
		String jsonStr = getResponseStr(url, xmlParam);
		logger.info("统一下单响应---"+jsonStr);
		if (jsonStr.indexOf(FAIL) != -1) {
			return "";
		}
		Map map = doXMLParse(jsonStr);
		return (String) map.get("code_url");
	}

	public static  Map<String,Object> orderQuery(String url, String xmlParam) {
		 Map<String,Object> map = new HashMap<String,Object>();
		try {
			String jsonStr = getResponseStr(url, xmlParam);
			logger.info("订单查询响应---"+jsonStr);
			if(jsonStr.indexOf(FAIL)!=-1){
				return map;
			}
			map = doXMLParse(jsonStr);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return map;
	}

	/**
	 * 解析xml,返回第一级元素键值对。如果第一级元素有子节点，则此节点的值是子节点的xml数据。
	 * 
	 * @param strxml
	 * @return
	 * @throws JDOMException
	 * @throws IOException
	 */
	public static  Map<String,Object> doXMLParse(String strxml) throws Exception {
		if (null == strxml || "".equals(strxml)) {
			return null;
		}

		 Map<String,Object> m = new HashMap<String,Object>();
		InputStream in = String2Inputstream(strxml);
		SAXBuilder builder = new SAXBuilder();
		Document doc = builder.build(in);
		Element root = doc.getRootElement();
		List list = root.getChildren();
		Iterator it = list.iterator();
		while (it.hasNext()) {
			Element e = (Element) it.next();
			String k = e.getName();
			String v = "";
			List children = e.getChildren();
			if (children.isEmpty()) {
				v = e.getTextNormalize();
			} else {
				v = getChildrenText(children);
			}

			m.put(k, v);
		}

		// 关闭流
		in.close();

		return m;
	}

	/**
	 * 获取子结点的xml
	 * 
	 * @param children
	 * @return String
	 */
	public static String getChildrenText(List children) {
		StringBuffer sb = new StringBuffer();
		if (!children.isEmpty()) {
			Iterator it = children.iterator();
			while (it.hasNext()) {
				Element e = (Element) it.next();
				String name = e.getName();
				String value = e.getTextNormalize();
				List list = e.getChildren();
				sb.append("<" + name + ">");
				if (!list.isEmpty()) {
					sb.append(getChildrenText(list));
				}
				sb.append(value);
				sb.append("</" + name + ">");
			}
		}

		return sb.toString();
	}

	public static InputStream String2Inputstream(String str) {
		return new ByteArrayInputStream(str.getBytes());
	}
	
	/**
	 * 获取随机字符串
	 * @return
	 */
	public static String getNonceStr() {
		// 随机数
		String currTime = TenpayUtil.getCurrTime();
		// 8位日期
		String strTime = currTime.substring(8, currTime.length());
		// 四位随机数
		String strRandom = TenpayUtil.buildRandom(4) + "";
		// 10位序列号,可以自行调整。
		return strTime + strRandom;
	}
	/**
	 * 元转换成分
	 * @param money
	 * @return
	 */
	public static String getMoney(String amount) {
		if(amount==null){
			return "";
		}
		// 金额转化为分为单位
		String currency =  amount.replaceAll("\\$|\\￥|\\,", "");  //处理包含, ￥ 或者$的金额  
        int index = currency.indexOf(".");  
        int length = currency.length();  
        Long amLong = 0l;  
        if(index == -1){  
            amLong = Long.valueOf(currency+"00");  
        }else if(length - index >= 3){  
            amLong = Long.valueOf((currency.substring(0, index+3)).replace(".", ""));  
        }else if(length - index == 2){  
            amLong = Long.valueOf((currency.substring(0, index+2)).replace(".", "")+0);  
        }else{  
            amLong = Long.valueOf((currency.substring(0, index+1)).replace(".", "")+"00");  
        }  
        return amLong.toString(); 
	}
	/**
	 * 将分转成元，而且保留两位小数点
	 * @param money 单位为分
	 * @return
	 */
	public static String getMoneyBy2Point(String money){
		DecimalFormat    df   = new DecimalFormat("######0.00"); 
		return df.format(Double.valueOf(money)/100);
	}
}